<template>
  <div>
    <el-form @submit.native.prevent>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item>
            <div style="display:flex">
              <el-input v-model="text" prefix-icon="el-icon-search" placeholder="请输入"
                        @keyup.enter.native="search()">
              </el-input>
              <el-button type="primary" @click="search()">查询
              </el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col v-if="role=='评估师'" :span="2">
          <el-form-item>
            <el-button type="primary" @click="add()">新建合同
            </el-button>
          </el-form-item>
        </el-col>
        <el-col v-if="role=='评估师'" :span="2">
          <el-form-item>
            <el-dropdown @command="handCommand">
              <el-button type="primary">使用模板
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="people">个人</el-dropdown-item>
                <el-dropdown-item command="company">企业机构</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!--表格内容-->
    <el-table ref="contractList" :data="tableData" style="width: 100%; margin-bottom: 5px;" border
              :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
      <el-table-column type="selection">
      </el-table-column>
      <el-table-column property="wthtbh" label="合同编号" width="120px">
        <!-- <template slot-scope="scope">
            <el-link :href="scope.row.url" target="_blank">{{ scope.row.wthtbh }}</el-link>
        </template> -->
      </el-table-column>
      <!-- <el-table-column property="cph" label="车辆号牌" width="100px">
</el-table-column> -->
      <el-table-column property="wtf" label="委托方">
      </el-table-column>
      <el-table-column property="wtflx" label="委托方类型" width="120px">
      </el-table-column>
      <el-table-column property="pgmd" label="评估目的">
      </el-table-column>

      <el-table-column property="date" label="合同时效" width="100px">
      </el-table-column>
      <el-table-column label="操作" width="160px">
        <template slot-scope="scope">
          <span v-if="role == '高级评估师' || role == '企业管理员'">
            <el-button v-if="scope.row.discard == '作废'" type="text"
                       @click="rowEdit(scope.row)">编辑</el-button>
            <el-tooltip :content="'委托合同文件模板：' + scope.row.templateName" placement="bottom" effect="light">
              <el-button v-if="scope.row.templateId != null" type="text" @click="view(scope.row.id)">预览</el-button>
            </el-tooltip>
            <el-tooltip :content="'委托合同文件模板：' + scope.row.templateName" placement="bottom" effect="light">
              <el-button v-if="scope.row.templateId != null" type="text" @click="downLoad(scope.row.id)">下载</el-button>
            </el-tooltip>

            <el-button v-if="scope.row.templateId == null" type="text"
                       @click="setTemplate(scope.row.id)">选择合同文件模板</el-button>
          </span>
          <span v-if="role == '评估师'">
            <el-dropdown @command="htCommand">
                <el-button v-if="scope.row.discard == '作废'" type="text"
                           @click="rowEdit(scope.row)">编辑</el-button>
              <!--                <el-dropdown-menu slot="dropdown">-->
              <!--                    <el-dropdown-item :command="{ obj: scope.row, str: 'view' }">预览</el-dropdown-item>-->
              <!--                    <el-dropdown-item v-if="scope.row.wtflx != '司法机构'"-->
              <!--                                      :command="{ obj: scope.row, str: 'download' }">下载</el-dropdown-item>-->
              <!--                  &lt;!&ndash; <el-dropdown-item command="upload">上传</el-dropdown-item> &ndash;&gt;-->
              <!--                </el-dropdown-menu>-->
            </el-dropdown>
            <el-button v-if="scope.row.discard == '作废'" type="text" @click="newBusiness(scope.row)"
                       style="margin-left:10px">创建业务</el-button>
            <el-button type="text" style="color:red" @click="rowDel(scope.row.id, scope.row.discard)">{{
                scope.row.discard
              }}</el-button>
          </span>
        </template>

      </el-table-column>
    </el-table>

    <el-drawer title="新建业务" ref="drawer" :visible.sync="drawer" direction="rtl" size="30%">
      <el-form :model="formFileds" :rules="rules" ref="formFileds" label-width="150px" class="demo-formFileds">
        <el-form-item label="合同编号：">
          <el-input type="text" v-model="wthtbh" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="业务类型：" prop="ywlx">
          <el-select v-model="formFileds.ywlx" clearable placeholder="请选择业务类型" style="width:100%" disabled>
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对接人：" prop="djr">
          <el-input type="text" v-model="formFileds.djr">
          </el-input>
        </el-form-item>
        <el-form-item label="评估师：" prop="pgs">
          <el-input type="text" v-model="formFileds.pgs" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label=" 开始时间：" prop="startTime">
          <el-date-picker v-model="formFileds.startTime" type="datetime" placeholder="选择日期时间"
                          default-time="12:00:00">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm()" class="pull-right margin-l-25">确定
          </el-button>
          <el-button class="pull-right" @click="drawerColse()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <contract-add v-if="addShow" :addShow="addShow" :qyid="id" @dialogClose="dialogClose"
                  @getList="getList"></contract-add>
    <Edit v-if="editShow" :editShow="editShow" :record="formFiled" @dialogClose="dialogClose" @getList="getList">
    </Edit>
    <!--分页-->
    <el-pagination :page-sizes="pageSizes" :page-size="pageSize" :current-page="pageNum" :total="total"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <el-dialog v-dialogDrag :visible="setTemplateVisible" title="选择模板" @close="dialogClose"
               :close-on-click-modal="true" width="40%">
      <vxe-table
        round
        stripe
        border
        align="center"

        :data="templates">
        <vxe-column field="fileViewName" title="模板"></vxe-column>
        <vxe-column field="cru" width="200" title="创建人"></vxe-column>

        <vxe-column width="100" title="操作">
          <template #default="{ row, rowIndex  }">
            <el-button type="primary" @click="selectTemplate(row)">选择</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </el-dialog>

  </div>
</template>

<script>
import ContractAdd from './contractAdd.vue';
import Edit from './contractEdit.vue';
import {selectAll, createYw, hetongzf, hetongqxzf, create, getPart} from "@/api/evaluation/contract";
import {correlationId} from '@/api/systemManage/enterpriseMaage';
import {findByName} from '@/api/systemManage/dataDictionary';
import {getByCompany, setTemplate, setWthtTemplate} from "@/api/template/template";

export default {
  name: "contractList",
  components: {
    Edit,
    ContractAdd,
  },
  data() {
    return {
      role: localStorage.getItem('role'),
      id: '',
      text: '',
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10],
      newForm: {},
      formFiled: {},
      formFileds: {
        wthtId: '',
        qyid: '',
        ywlx: '',
        djr: '',
        pgs: localStorage.getItem('username'),
        startTime: '',
        wtflx: ''
      },
      editShow: false,
      addShow: false,
      drawer: false,
      options: [],
      wthtbh: '',
      rules: {
        ywlx: [
          {required: true, message: '请选择业务类型', trigger: 'change,blur'}
        ],
        pgs: [
          {required: true, message: ' ', trigger: 'change,blur'}
        ],
        startTime: [
          {required: true, message: '请选择开始时间', trigger: 'change,blur'},
        ],
        wtflx: [
          {required: true, message: '请选择委托方类型', trigger: 'change,blur'}
        ],
      },
      setTemplateVisible: false,
      templates:[],
      wthtId:'',
    }
  },
  methods: {
    view(id) {
      let href = '/api/wtht/createWtht?wthtid=' + id + '&type=pdf&download=false'
      window.open(href, '_blank')
    },
    downLoad(id) {
      window.location.href = '/api/wtht/createWtht?wthtid=' + id + '&type=pdf&download=true'
    },
    setTemplate(id){
      this.setTemplateVisible = true;
      this.wthtId = id;
      getByCompany("ywlx=合同模板").then(
        (res) => {
          this.templates = res.data
        }
      )
    },
    selectTemplate(row) {
      setWthtTemplate("templateId=" + row.id + "&wthtId=" + this.wthtId)
      this.getList()
      this.setTemplateVisible = false
      this.wthtId = ''
    },
    htCommand(command) {
      if (command.str == 'view') {
        let href = '/api/wtht/createWtht?wthtid=' + command.obj.id + '&type=pdf&download=false'
        window.open(href, '_blank')
      } else if (command.str == 'download') {
        window.location.href = '/api/wtht/createWtht?wthtid=' + command.obj.id + '&type=pdf&download=true'

      }
    },
    dialogClose() {
      this.addShow = false;
      this.editShow = false;
      this.setTemplateVisible = false;
    },
    rowEdit(row) {
      // //当前选中行
      this.formFiled = row;
      this.editShow = true;
    },
    add() {
      this.addShow = true
    },
    drawerColse() {
      this.drawer = false
    },
    newBusiness(row) {
      this.formFileds = {
        wthtId: row.id,
        qyid: row.qyid,
        ywlx: row.ywlx,
        djr: '',
        pgs: localStorage.getItem('username'),
        startTime: '',
        wtflx: ''
      }
      this.drawer = true
      this.wthtbh = row.wthtbh
    },
    handCommand(command) {
      if (command == 'people') {
        var qyid = this.id
        this.newForm = {
          qyid,
          wtflx: '个人',
          wthtlx: '',
          wtf: '',
          wtfXydm: '',
          pgmd: '',
          pgjzr: '',
          cjbgsj: '',
        }
        this.$confirm("确定要使用个人委托合同模板吗？", "个人委托", {
          comfirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          create(this.newForm).then((res) => {
            if (res) {
              this.$message.success("使用成功！");
              this.getList();
            }
          });
        });
      } else {
        var qyid = this.id
        this.newForm = {
          qyid,
          wtflx: '企业机构',
          wthtlx: '',
          wtf: '',
          wtfFrSqdb: '',
          wtfXydm: '',
          wtfDz: '',
          pgmd: '',
          pgjzr: '',
          cjbgsj: '',
        }
        this.$confirm("确定要使用企业委托合同模板吗？", "企业委托", {
          comfirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          create(this.newForm).then((res) => {
            if (res) {
              this.$message.success("使用成功！");
              this.getList();
            }
          });
        });
      }
    },
    rowDel(id, discard) {
      if (discard == '作废') {
        this.$confirm('确定要作废该合同吗？', '作废', {
          comfirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          hetongzf('id=' + id).then((res) => {
            this.getList()
          })
        });
      } else {
        this.$confirm('确定要重新实施该合同吗？', '启用', {
          comfirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          hetongqxzf('id=' + id).then((res) => {
            this.getList()
          })
        });
      }

    },
    dataDictionaryList() {
      findByName('input=' + '业务类型').then((res) => {
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].dictName == '业务类型')
            this.options.push({
              label: res.data[i].dictValue,
              value: res.data[i].dictValue
            })
        }
      })
    },
    search() {
      getPart('qyid=' + this.id + '&input=' + this.text + '&pageNum=' + this.pageNum + '&pageSize=' + this.pageSize).then((res) => {
        this.tableData = res.data.list
        this.total = res.data.total
        this.tabletest()
      })
    },
    handleSizeChange(e) {
      this.pageSize = e
      if (this.input) {
        this.search()
      } else {
        this.getList()
      }

    },
    handleCurrentChange(e) {
      this.pageNum = e
      if (this.input) {
        this.search()
      } else {
        this.getList()
      }
    },
    getList() {
      let params = localStorage.getItem('userId')
      correlationId('userId=' + params).then((res) => {
        this.id = res.data.companyId
        // this.id=1

        selectAll('qyid=' + this.id + '&pageNum=' + this.pageNum + '&pageSize=' + this.pageSize).then((res) => {
          this.tableData = res.data.list
          this.total = res.data.total
          this.tabletest()
        })
      })
    },
    tabletest() {
      this.pageSizes = []
      let all = Math.ceil(this.total / 10)
      for (let i = 0; i < all; i++) {

        this.pageSizes.push(10 * (i + 1))
      }
      if (this.tableData) {
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].url = 'http://www.jianpingyun.com/api/wtht/createWtht3?wthtid=' + this.tableData[i].id
          var shijian = this.dateTrs(this.tableData[i].qyrq, this.tableData[i].cjbgsj)
          if (shijian >= 0) {
            this.tableData[i].date = "剩余 " + shijian + " 天"
          } else {
            this.tableData[i].date = '未开始'
          }
          if (this.tableData[i].htzt == '正常') {
            this.tableData[i].discard = "作废"
          } else {
            this.tableData[i].discard = "启用"
          }
        }
      }
    },
    dateTrs(qysj, bgsj) {
      if (qysj) {
        var date1 = (new Date(qysj)).getTime()
        var date2 = parseInt(bgsj) * 24 * 3600 * 1000
        var date3 = (new Date()).valueOf()
        // date3 = date3.valueOf()
        var date4 = parseInt((parseInt(date1) + parseInt(date2) - parseInt(date3)) / (24 * 3600 * 1000))
        return date4
      } else {
        return -1
      }
    },
    submitForm() {
      this.$refs.formFileds.validate((valid) => {
        if (valid) {
          createYw(this.formFileds).then((res) => {
            if (res.code == 200) {
              this.$message.success('创建成功')
              this.drawer = false
              this.formFileds = {}
            }
            // else{
            //     this.$message.error(res.msg)
            // }
          })
        } else {
          return
        }
      });
    },

  },
  mounted() {
    this.getList()
    this.dataDictionaryList()
  }
}
</script>

<style scoped lang="less">
.el-form {
  padding: 0 10px;
}

.el-date-editor {
  width: 100% !important;
}

.demo-formFileds {
  padding-right: 50px;
}

/deep/ .el-drawer__header {
  background-color: #2EB3FF;
  align-items: center;
  color: #fff;
  height: 60px;
  margin-bottom: 15px;
  font-weight: bold;

}
</style>
